var webim = require('webim_wx.js');
var Api = require('api.js');
var selToID, loginInfo, accountMode, accountType, sdkAppID, selType, selToID, selSess, selSessHeadUrl, that;
// try {
//     userInfo = JSON.parse(wx.getStorageSync("userInfo"));
// } catch (e) {
//     Api.login({
//         cb: function (res) {
//             userInfo = res;
//         }
//     });
// }
var app = getApp();

//sdk登录
function sdkLogin(that, selToID, userInfo, callback) {
    //web sdk 登录
    this.init({
        accountMode: app.data.Config.accountMode,
        accountType: app.data.Config.accountType,
        sdkAppID: app.data.Config.sdkappid,
        selType: webim.SESSION_TYPE.C2C, //私聊
        selToID: selToID,
        that: that
    });

    //当前用户身份
    var loginInfo2 = {
        sdkAppID: app.data.Config.sdkappid, //用户所属应用id,必填
        appIDAt3rd: app.data.Config.sdkappid, //用户所属应用id，必填
        accountType: app.data.Config.accountType, //用户所属应用帐号类型，必填
        identifier: userInfo.Identifier, //当前用户ID,必须是否字符串类型，选填
        identifierNick: userInfo.nickName, //当前用户昵称，选填
        userSig: userInfo.userSig //当前用户身份凭证，必须是字符串类型，选填
    };

    //监听连接状态回调变化事件
    var onConnNotify = function (resp) {
        switch (resp.ErrorCode) {
        case webim.CONNECTION_STATUS.ON:
            // webim.Log.warn("连接状态正常...");
            break;
        case webim.CONNECTION_STATUS.OFF:
            webim.Log.warn(
                "连接已断开，无法收到新消息，请检查下你的网络是否正常"
            );
            break;
        default:
            webim.Log.error("未知连接状态,status=" + resp.ErrorCode);
            break;
        }
    };

    //监听事件
    var listeners = {
        onConnNotify: onConnNotify, //选填
        onMsgNotify: onMsgNotify //监听新消息(私聊(包括普通消息和全员推送消息)，普通群(非直播聊天室)消息)事件，必填
    };

    //其他对象，选填
    var options = {
        isAccessFormalEnv: true, //是否访问正式环境，默认访问正式，选填
        isLogOn: false //是否开启控制台打印日志,默认开启，选填
    };

    // console.log(userInfo)
    webim.login(loginInfo2, listeners, options,
        function (resp) {
            loginInfo = loginInfo2;
            callback()
        },
        function (err) {
            console.error("登录失败", err);
        }
    );

}

//监听新消息(私聊(包括普通消息、全员推送消息)，普通群(非直播聊天室)消息)事件
//newMsgList 为新消息数组，结构为[Msg]
function onMsgNotify(newMsgList) {
    var newMsg;
    for (var j in newMsgList) { //遍历新消息
        newMsg = newMsgList[j];
        //处理新消息
        handlderMsg(newMsg);
    }
    getUnread();
}

//获取消息未读数并更新到会话列表
function getUnread() {
    var sess = {};
    var sessMap = webim.MsgStore.sessMap();
    if (that.data.contactList) { //这里判断是否存在会话列表，或者在会话列表的页面
        // 更新消息的未读数
        for (var i in sessMap) {
            sess = sessMap[i];
            var contactList = that.data.contactList.map((item, index) => {
                if (item.To_Account == sess.id()) {
                    item.UnreadMsgCount = sess.unread()
                }
                return item;
            })
            //先把未读数赋值
            that.setData({
                contactList: contactList
            })
            // 获取最新的会话消息（把最新的一条赋值到会话列表）
            webim.getRecentContactList({
                'Count': 20 //最近的会话数 ,最大为 100
            }, function (resp) {
                var MsgShow = resp.SessionItem.filter((item, index) => {
                    if (item.To_Account == sess.id()) return item;
                })
                var contactList = that.data.contactList.map((item, index) => {
                    if (item.To_Account == sess.id()) {
                        item.MsgShow = MsgShow[0].MsgShow
                    }
                    return item;
                })
                that.setData({
                    contactList: contactList
                })
            })
        }
    }
}


//处理消息（私聊(包括普通消息和全员推送消息)，普通群(非直播聊天室)消息）
function handlderMsg(msg) {
    var fromAccount, fromAccountNick, sessType, sessId, subType, contentHtml, isSend, time;
    fromAccount = msg.getFromAccount();
    if (!fromAccount) {
        fromAccount = '';
    }
    fromAccountNick = msg.getFromAccountNick();
    if (!fromAccountNick) {
        fromAccountNick = fromAccount;
    }
    isSend = msg.getIsSend();
    time = msg.getTime();
    //解析消息
    sessId = msg.getSession().id();
    sessType = msg.getSession().type();
    subType = msg.getSubType();
    switch (sessType) {
    case webim.SESSION_TYPE.C2C: //私聊消息
        switch (subType) {
        case webim.C2C_MSG_SUB_TYPE.COMMON: //c2c普通消息
            contentHtml = convertMsgtoHtml(msg);
            var msgs = {
                time: time,
                isSend: isSend,
                sessId: sessId,
                fromAccount: fromAccount,
                fromAccountNick: fromAccountNick,
                content: contentHtml
            }
            that.receiveMsgs(msgs)
            break;
        }
        break;
    case webim.SESSION_TYPE.GROUP: //普通群消息，对于直播聊天室场景，不需要作处理
        break;
    }
}

function getC2CHistoryMsgs(cbOk, cbError) {
    if (!selToID || selToID == '@TIM#SYSTEM') {
        console.error('当前的聊天id非法，selToID=' + selToID);
        return;
    }
    var lastMsgTime = 0; //第一次拉取好友历史消息时，必须传 0
    var msgKey = wx.getStorageSync('msgKey') || '';
    var options = {
        'Peer_Account': selToID, //好友帐号
        'MaxCnt': 10, //拉取消息条数
        'LastMsgTime': lastMsgTime, //最近的消息时间，即从这个时间点向前拉取历史消息
        'MsgKey': msgKey
    };
    webim.getC2CHistoryMsgs(
        options,
        function (resp) {
            var complete = resp.Complete; //是否还有历史消息可以拉取，1-表示没有，0-表示有
            var retMsgCount = resp.MsgCount; //返回的消息条数，小于或等于请求的消息条数，小于的时候，说明没有历史消息可拉取了
            if (resp.MsgList.length == 0) {
                return;
            }
            wx.setStorageSync('lastMsgTime', resp.LastMsgTime);
            wx.setStorageSync('msgKey', resp.MsgKey);
            if (cbOk)
                cbOk(resp.MsgList);
        },
        cbError
    );
}

function getHistoryMsgCallback(msgList) {
    var msg;
    for (var j in msgList) { //遍历新消息
        msg = msgList[j];
        if (msg.getSession().id() == selToID) { //为当前聊天对象的消息
            selSess = msg.getSession();
            //在聊天窗体中新增一条消息
            handlderMsg(msg);
        }
    }
    //消息已读上报，并将当前会话的消息设置成自动已读
    webim.setAutoRead(selSess, true, true);
}


//显示消息（群普通+点赞+提示+红包）
function showMsg(msg) {
    var isSend, fromAccount, fromAccountNick, sessType, sessId, subType, time;
    fromAccount = msg.getFromAccount();
    if (!fromAccount) {
        fromAccount = '';
    }
    fromAccountNick = msg.getFromAccountNick();
    if (!fromAccountNick) {
        fromAccountNick = '未知用户';
    }
    isSend = msg.getIsSend();
    time = msg.getTime();
    //解析消息
    sessId = msg.getSession().id();
    sessType = msg.getSession().type();
    subType = msg.getSubType();

    var contentHtml = "";
    switch (subType) {
    case webim.GROUP_MSG_SUB_TYPE.COMMON: //群普通消息
        contentHtml = convertMsgtoHtml(msg);
        break;
    case webim.GROUP_MSG_SUB_TYPE.REDPACKET: //群红包消息
        contentHtml = "[群红包消息]" + convertMsgtoHtml(msg);
        break;
    case webim.GROUP_MSG_SUB_TYPE.LOVEMSG: //群点赞消息
        //业务自己可以增加逻辑，比如展示点赞动画效果
        contentHtml = "[群点赞消息]" + convertMsgtoHtml(msg);
        //展示点赞动画
        break;
    case webim.GROUP_MSG_SUB_TYPE.TIP: //群提示消息
        contentHtml = "[群提示消息]" + convertMsgtoHtml(msg);
        break;
    }
    return {
        time: time,
        isSend: isSend,
        sessId: sessId,
        fromAccount: fromAccount,
        fromAccountNick: fromAccountNick,
        content: contentHtml
    }
}

//把消息转换成Html
function convertMsgtoHtml(msg) {
    var html = "",
        elems, elem, type, content;
    elems = msg.getElems(); //获取消息包含的元素数组
    for (var i in elems) {
        elem = elems[i];
        type = elem.getType(); //获取元素类型
        content = elem.getContent(); //获取元素对象
        switch (type) {
        case webim.MSG_ELEMENT_TYPE.TEXT:
            html += convertTextMsgToHtml(content);
            break;
        default:
            webim.Log.error('未知消息元素类型: elemType=' + type);
            break;
        }
    }
    return webim.Tool.formatHtml2Text(html);
}

//解析文本消息元素
function convertTextMsgToHtml(content) {
    return content.getText();
}

//发送消息(普通消息)
function onSendMsg(msg, callback) {
    if (!loginInfo.identifier) { //未登录
        if (accountMode == 1) { //托管模式
            tlsLogin();
        } else { //独立模式
            console.error('请填写帐号和票据');
        }
        return;
    }

    if (!selToID) {
        console.error("您还没有进入房间，暂不能聊天");
        return;
    }
    //获取消息内容
    var msgtosend = msg;
    var msgLen = webim.Tool.getStrBytes(msg);

    if (msgtosend.length < 1) {
        console.error("发送的消息不能为空!");
        return;
    }

    var maxLen, errInfo;
    if (selType == webim.SESSION_TYPE.GROUP) {
        maxLen = webim.MSG_MAX_LENGTH.GROUP;
        errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
    } else {
        maxLen = webim.MSG_MAX_LENGTH.C2C;
        errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
    }
    if (msgLen > maxLen) {
        console.error(errInfo);
        return;
    }

    if (!selSess) {
        selSess = new webim.Session(selType, selToID, selToID, selSessHeadUrl, Math.round(new Date().getTime() / 1000));
    }
    var isSend = true; //是否为自己发送
    var seq = -1; //消息序列，-1表示sdk自动生成，用于去重
    var random = Math.round(Math.random() * 4294967296); //消息随机数，用于去重
    var msgTime = Math.round(new Date().getTime() / 1000); //消息时间戳
    var subType; //消息子类型
    if (selType == webim.SESSION_TYPE.GROUP) {
        subType = webim.GROUP_MSG_SUB_TYPE.COMMON;
    } else {
        subType = webim.C2C_MSG_SUB_TYPE.COMMON;
    }
    var msg = new webim.Msg(selSess, isSend, seq, random, msgTime, loginInfo.identifier, subType, loginInfo.identifierNick);
    //解析文本和表情
    var expr = /\[[^[\]]{1,3}\]/mg;
    var emotions = msgtosend.match(expr);
    var text_obj, face_obj, tmsg, emotionIndex, emotion, restMsgIndex;
    if (!emotions || emotions.length < 1) {
        text_obj = new webim.Msg.Elem.Text(msgtosend);
        msg.addText(text_obj);
    } else { //有表情

        for (var i = 0; i < emotions.length; i++) {
            tmsg = msgtosend.substring(0, msgtosend.indexOf(emotions[i]));
            if (tmsg) {
                text_obj = new webim.Msg.Elem.Text(tmsg);
                msg.addText(text_obj);
            }
            emotionIndex = webim.EmotionDataIndexs[emotions[i]];
            emotion = webim.Emotions[emotionIndex];
            if (emotion) {
                face_obj = new webim.Msg.Elem.Face(emotionIndex, emotions[i]);
                msg.addFace(face_obj);
            } else {
                text_obj = new webim.Msg.Elem.Text(emotions[i]);
                msg.addText(text_obj);
            }
            restMsgIndex = msgtosend.indexOf(emotions[i]) + emotions[i].length;
            msgtosend = msgtosend.substring(restMsgIndex);
        }
        if (msgtosend) {
            text_obj = new webim.Msg.Elem.Text(msgtosend);
            msg.addText(text_obj);
        }
    }
    webim.sendMsg(msg, function (resp) {
        if (selType == webim.SESSION_TYPE.C2C) { //私聊时，在聊天窗口手动添加一条发的消息，群聊时，长轮询接口会返回自己发的消息
            showMsg(msg);
        }
        callback && callback();
    }, function (err) {
        webim.Log.error("发消息失败:" + err.ErrorInfo);
        console.error("发消息失败:" + err.ErrorInfo);
    });
}


function init(opts) {
    accountMode = opts.accountMode;
    accountType = opts.accountType;
    sdkAppID = opts.sdkAppID;
    selType = opts.selType;
    selToID = opts.selToID;
    that = opts.that;
}

module.exports = {
    init: init,
    onMsgNotify: onMsgNotify,
    sdkLogin: sdkLogin,
    showMsg: showMsg,
    convertMsgtoHtml: convertMsgtoHtml,
    convertTextMsgToHtml: convertTextMsgToHtml,
    getC2CHistoryMsgs: getC2CHistoryMsgs,
    getHistoryMsgCallback: getHistoryMsgCallback,
    onSendMsg: onSendMsg,
};